import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import {
    getAuth
} from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import Watermark from '@/utils/watermark';

NProgress.configure({
    showSpinner: false
})
// NProgress Configuration

// 白名单路由配置 
const whiteList = ['/login', '/calogin', '/unifyLogin', '/first_login', '/auth-redirect', '/403', '/404',] // no redirect whitelist
//注意：确定自己避免了路由守卫进入死循环
//let oneRun = true; //通过oneRun变量控制 避免陷入死循环
let authorRoutes = []
router.beforeEach(async (to, from, next) => {
    // start progress bar
    NProgress.start()
    // set page title
    document.title = getPageTitle(to.meta.title)
    // determine whether the user has logged in
    const hasToken = getAuth('T');
    const roles = getAuth("R");

    if (hasToken) {
        if (to.path === '/login' || to.path === '/unifyLogin' || to.path === '/calogin' || to.path === '/') {
                // 测试 默认静态页面
                store.dispatch('permission/generateRoutes', store.getters.roles).then(accessRoutes => {
                    // 根据roles权限生成可访问的路由表
   
                    //   router.addRoute(accessRoutes) // 动态添加可访问路由表
                    for (let i = 0; i< accessRoutes.length; i++){
                        const element = accessRoutes[i];
                        router.addRoute(element)
                    }
                    //   next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
                })
            next({
                path: '/manager/index',
                replace: true
            });
            NProgress.done(); 
        } 
        else if (to.path === '/404' || to.path === '/403') {
            next();
        } else {
            if(store.getters.oneRun == 'true') {
                /* 获取该角色所有权限路由列表 */
                authorRoutes = await store.dispatch("user/getAuthor");
                //oneRun = false;//必须在creatNewRouter() 执行
                store.commit('permission/SET_ONERUN','false');
                // 测试 默认静态页面
                store.dispatch('permission/generateRoutes', store.getters.roles).then(accessRoutes => {
                    // 根据roles权限生成可访问的路由表
                    //   router.addRoute(accessRoutes) // 动态添加可访问路由表

                    //accessRoutes.splice(5,1)
                    for (let i = 0; i< accessRoutes.length; i++){
                        const element = accessRoutes[i];
                        router.addRoute(element)
                    }
                })
            }
            let index = authorRoutes.findIndex(item=>'/'+item == to.path)
            if (index != -1) {
                next();
                NProgress.done();
            } else {
                /* 自定义尺寸重定向刷新 */
                if (to.path.indexOf('/redirect/') > -1) {
                    next();
                } else {
                    next('/403');
                }
            }
        }
    } else {
        /* has no token*/
        if (whiteList.indexOf(to.path) !== -1) {
            // in the free login whitelist, go directly
            next()
        } else {
            //登录过期时，根据之前登录方式，跳转对应登录页
            let loginType = localStorage.getItem("loginType");
            if(loginType == 'login'){
                //账号登录页面
                next(`/login?redirect=${to.path}`)
                NProgress.done()
            }else if(loginType == 'caLogin'){
                //ca登录页面
                next(`/calogin?redirect=${to.path}`)
                NProgress.done()
            }else if(loginType == 'unifyLogin'){
                //统一登录门户
                window.location.href = 'https://xyjg.nantong.cn/sso/menhu'
            }else{
                //默认账号登录（东站、政内）
                next(`/login?redirect=${to.path}`)
                //默认ca登录（金融机构）
                //next(`/calogin?redirect=${to.path}`)
                NProgress.done()
            }
        }
    }
})

router.afterEach((item) => {
    // finish progress bar
    if(item.path == '/login' || item.path == '/calogin' || item.path == '/unifyLogin' || item.path == '/404' || item.path == '/403' ){
        Watermark.out()
    }else{
        store.dispatch("user/getUserMsg").then(res=>{
            Watermark.set(res)
          });
    }
    NProgress.done()
})
